package com.jp.game.ui.home;

import static com.jp.game.common.Constant.DATE_REFRESH;
import static com.jp.game.common.Constant.LEVEL_FOUR;
import static com.jp.game.common.Constant.LEVEL_ONE;
import static com.jp.game.common.Constant.LEVEL_THREE;
import static com.jp.game.common.Constant.LEVEL_TWO;
import static com.jp.game.common.Constant.SHOT_ONE;
import static com.jp.game.common.Constant.SHOT_THREE;
import static com.jp.game.common.Constant.SHOT_TWO;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.TypeReference;
import com.jp.game.common.Constant;
import com.jp.game.common.Result;
import com.jp.game.databinding.FragmentHomeBinding;
import com.jp.game.utils.SPUtil;
import com.jp.game.utils.ToastUtil;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;
import com.qmuiteam.qmui.widget.pullRefreshLayout.QMUIPullRefreshLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class HomeFragment extends Fragment implements View.OnClickListener {

    private static final String TAG = HomeFragment.class.getSimpleName();

    private FragmentHomeBinding binding;

    GameAdapter gameAdapter = null;

    private List<Game> gameList = new ArrayList<>();

    private QMUIPullRefreshLayout mPullRefreshLayout;

    QMUITipDialog qmuiTipDialog = null;

    private RecyclerView recyclerView;

    private ImageView noDataIv;

    private Timer timer = new Timer();

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        EventBus.getDefault().register(this);

        qmuiTipDialog = new QMUITipDialog.Builder(getContext())
                .setIconType(QMUITipDialog.Builder.ICON_TYPE_LOADING).setTipWord("加载中...").create();

        binding = FragmentHomeBinding.inflate(inflater, container, false);
        View root = binding.getRoot();
        noDataIv = binding.noDataIv;
        mPullRefreshLayout = binding.pullToRefresh;
        recyclerView = binding.recyclerView;
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        recyclerView.setLayoutManager(layoutManager);
        gameAdapter = new GameAdapter(getActivity(), gameList);
        recyclerView.setAdapter(gameAdapter);

        mPullRefreshLayout.setOnPullListener(new QMUIPullRefreshLayout.OnPullListener() {
            @Override
            public void onMoveTarget(int offset) {

            }

            @Override
            public void onMoveRefreshView(int offset) {

            }

            @Override
            public void onRefresh() {
                initGame();
                mPullRefreshLayout.finishRefresh();
            }
        });

        initGame();
        initRefresh();
        return root;
    }

    private void initGame() {
        getActivity().runOnUiThread(new Runnable() {
            public void run() {
                qmuiTipDialog.show();
            }
        });

        //1.创建OkHttpClient对象
        OkHttpClient okHttpClient = new OkHttpClient();
        //2.创建Request对象，设置一个url地址,设置请求方式。
        List<BetQueryRequest> betQueryRequests = new ArrayList<>();
        BetQueryRequest queryPo = new BetQueryRequest();
        queryPo.setEndWaterLevel(Float.valueOf(SPUtil.getString("levelTwo", LEVEL_TWO)));
        queryPo.setShootScore(Integer.valueOf(SPUtil.getString("shotOne", SHOT_ONE)));
        queryPo.setStartWaterLevel(Float.valueOf(SPUtil.getString("levelOne", LEVEL_ONE)));
        betQueryRequests.add(queryPo);

        queryPo = new BetQueryRequest();
        queryPo.setEndWaterLevel(Float.valueOf(SPUtil.getString("levelFour", LEVEL_FOUR)));
        queryPo.setGlobalRight(Integer.valueOf(SPUtil.getString("shotTwo", SHOT_TWO)));
        queryPo.setStartWaterLevel(Float.valueOf(SPUtil.getString("levelThree", LEVEL_THREE)));
        queryPo.setTime(Long.valueOf(SPUtil.getString("shotThree", SHOT_THREE)));
        betQueryRequests.add(queryPo);

        String json = JSONArray.toJSONString(betQueryRequests);
        Log.e(TAG, "请求参数 " + json);
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), json);
        Request request = new Request.Builder().url(Constant.API + "/bet/query").post(body).build();
        //3.创建一个call对象,参数就是Request请求对象
        Call call = okHttpClient.newCall(request);
        //4.同步调用会阻塞主线程,这边在子线程进行
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //同步调用,返回Response,会抛出IO异常
                    Response response = call.execute();
                    if (response.code() == 200) {
                        Result<List<BetQueryResponse>> result = JSON.parseObject(response.body().string(), new TypeReference<Result<List<BetQueryResponse>>>() {
                        });
                        Log.e(TAG, "接口调用返回对象 " + JSON.toJSONString(result));
                        if (result.getCode() == 0) {
                            List<BetQueryResponse> list = result.getData();

                            gameList = new ArrayList<>();
                            for (int i = 0; i < list.size(); i++) {
                                BetQueryResponse betQueryResponse = list.get(i);
                                Game game = new Game();
                                game.setOneTeam(betQueryResponse.getHomeTeamName());
                                game.setTwoTeam(betQueryResponse.getAwayTeamName());
                                game.setBall("" + betQueryResponse.getGlobalRight());
                                game.setTime(betQueryResponse.getTime());
                                game.setShoot("" + betQueryResponse.getShootScore());
                                game.setJumpUrl(betQueryResponse.getUrl());
                                gameList.add(game);
                            }
                        }

                        EventBus.getDefault().post("refresh_end");
                    } else {
                        EventBus.getDefault().post("call_fail");
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void initRefresh() {
        if (timer != null) {
            timer.cancel();
        }
        timer = new Timer();
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                initGame();
            }
        };
        String period = SPUtil.getString("dateRefresh", DATE_REFRESH);
        long periodL = Long.valueOf(period);
        timer.schedule(task, periodL, periodL);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
        if (timer != null) {
            timer.cancel();
        }
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onClick(View view) {
        System.out.printf("in");
    }

    @Subscribe
    public void onEvent(String eventName) {
        if ("refresh_home".equals(eventName)) {
            initGame();
            initRefresh();
            if (qmuiTipDialog != null) {
                qmuiTipDialog.hide();
            }
        } else if ("refresh_end".equals(eventName)) {
            getActivity().runOnUiThread(new Runnable() {
                public void run() {
                    if (gameList != null && gameList.size() > 0) {
                        recyclerView.setVisibility(View.VISIBLE);
                        recyclerView.scrollToPosition(0);
                        noDataIv.setVisibility(View.GONE);
                        gameAdapter.setNewList(gameList);
                        gameAdapter.notifyDataSetChanged();
                    } else {
                        recyclerView.setVisibility(View.GONE);
                        noDataIv.setVisibility(View.VISIBLE);
                    }
                    if (qmuiTipDialog != null) {
                        qmuiTipDialog.hide();
                    }
                }
            });
        } else if ("call_fail".equals(eventName)) {
            getActivity().runOnUiThread(new Runnable() {
                public void run() {
                    recyclerView.setVisibility(View.GONE);
                    noDataIv.setVisibility(View.VISIBLE);
                    ToastUtil.show(getActivity(), "接口调用失败");
                }
            });
        }
    }
}